package com.panshi.config;

import com.panshi.realm.CustomerRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * shiro 配置类
 */
@Configuration
public class ShiroConfig {

    //1.创建realm对象,需要自定义类 UserRealm extends AuthorizingRealm
    @Bean(name = "customerRealm")
    public Realm customerRealm(){
        return new CustomerRealm();
    }

    //2.
    @Bean(name="defaultWebSecurityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("customerRealm") Realm realm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        //关联realm对象
        manager.setRealm(realm);
        return manager;
    }

    //3.
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager manager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //bean.getFilters().put("authc", new MyFormAuthenticationFilter());
        //设置安全管理器
        bean.setSecurityManager(manager);

        //添加shiro的内置过滤器,拦截
        /**
         * anon : 无需认证就可访问
         * authc : 必须认证了才可访问
         * user: 必须拥有 记住我 功能才能访问
         * perms : 拥有对每个资源的权限才能方法
         * role : 拥有某个角色权限才能访问
         */
        Map<String,String>  filterMap = new LinkedHashMap<>();

        //无需授权的公共页面
        filterMap.put("/api/open/**","anon");



        //需要授权才能访问的页面
       // filterMap.put("/api/**","authc");

        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        //bean.setLoginUrl("/api/open/noauth");


        //未授权页面
        bean.setUnauthorizedUrl("/api/open/noauth");

        return bean;
    }

    /**
     * 解决方法上加了@RequiresPermissions注解同一个controller中其他方法也访问不到的问题
     * @return
     */
    @Bean
    public static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setUsePrefix(true);
        return defaultAdvisorAutoProxyCreator;
    }

}
